package com.zzyl.base;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.github.pagehelper.Page;
import io.swagger.annotations.ApiModel;
import lombok.*;

import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@ApiModel(value = "分页结果包装", description = "分页结果包装")
public class PageResponse<T> {

    private Long total = 0L;//总条目数
    private Integer pageSize = 0;//页尺寸
    private Long pages = 0L;//总页数
    private Integer page = 0;//页码
    private List<T> records = List.of();//数据列表

    //返回一个分页对象实例
    public static <T> PageResponse<T> of() {
        return PageResponse.<T>builder().build();
    }

    //Page对象封装为PageResponse，并将Page中的Records转换为指定类型封装为items
    public static <T> PageResponse<T> of(Page<?> page, Class<T> clazz) {
        return PageResponse.<T>builder()
                .page(page.getPageNum())
                .pageSize(page.getPageSize())
                .pages(Convert.toLong(page.getPages()))
                .total(page.getTotal())
                .records(BeanUtil.copyToList(page.getResult(), clazz))
                .build();
    }
}
